import { Component } from '@angular/core';

import { NavController, ViewController} from 'ionic-angular';

import { Storage } from '@ionic/storage';

import { Common } from "../../../providers/common";

import _ from "lodash";
import {DraftDetailService} from "./detail.service";

@Component({
	selector: 'modal-draft-addr',
	templateUrl: 'addr.modal.html',
  providers: [DraftDetailService]
})
export class DraftAddrModal{
	moa_page_name: any = "modal-draft-addr";
  moa_page_explain: any = "选择出差地点";
  dataList = [];
  dataListSource = [];

  isSelectAll = false;

  isNoMoreData = false;

  keyWord = "";

	constructor(
		public navCtrl: NavController,
    public common: Common,
    private draftDetailService: DraftDetailService,
    public viewCtrl: ViewController,
    public storage: Storage
	) {

  }

  updateList() {
	  if (this.keyWord) {
	    this.dataList = this.dataListSource;
	    this.dataList = _.filter(this.dataList, data => {
	      return data["entry"]["province_city"].indexOf(this.keyWord) > -1;
      });
    } else {
	    this.dataList = this.dataListSource;
    }
  }

  selectAll() {
	  if (this.isSelectAll) {
      _.forEach(this.dataList, fund => {
        fund["selected"] = true;
      });
    } else {
      _.forEach(this.dataList, fund => {
        fund["selected"] = false;
      });
    }
  }

  ionViewDidEnter() {
      let selectedAddr = this.viewCtrl.getNavParams().get("selectedAddr");
      console.log(selectedAddr);
      this.draftDetailService.getAddress().subscribe(datas => {
        console.log(datas);
        if (datas) {
          this.dataList = datas;
          this.dataListSource = datas;
          if (this.dataList.length <= 0) {
            this.isNoMoreData = true;
          }
          _.forEach(this.dataList, data => {
            let temp = _.find(selectedAddr, sa => {
              return sa["entry"]["province_city"] == data["entry"]["province_city"];
            });
            if (temp) {
              data["selected"] = true;
            } else {
              data["selected"] = false;
            }
          });

          if (this.dataList.length == selectedAddr.length) {
            this.isSelectAll = true;
          }
        } else {
          this.isNoMoreData = true;
        }
      });
  }

  closeModal() {
    this.viewCtrl.dismiss("close");
  }

  completeModal() {
	  let list = _.filter(this.dataList, {selected: true});
	  this.viewCtrl.dismiss(list);
  }


}

